package com.liusuai.yixian.page;

import com.alibaba.fastjson.JSONObject;
import com.liusuai.yixian.domain.ResultBean;
import com.liusuai.yixian.config.LoginInterceptor;
import com.liusuai.yixian.login.LoginControler;
import com.liusuai.yixian.login.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class PageControler {

    @Autowired
    private LoginControler loginControler;
    @Autowired
    private LoginInterceptor loginInterceptor;

    /**
     * 本地访问内容地址 ：http://localhost:8011/yixian/hello
     * 这一段代码中，我传递了一个表单对象到了前台界面中，如果我们不这么做，就会找不到表单对象提交的那个实体类了。
     */
    @RequestMapping(value = "/hello"
            , method = RequestMethod.GET)
    public String helloHtml(ModelMap map, HttpServletRequest request) {

        System.out.println("/hello request");

        String result = request.getParameter("result");
        if (result != null && result.equals("error")) {
            map.put("msg", "用户名或者密码错误!");
        }
        map.put("userlogin", new UserBean());

        return "/login";
    }

    //刷新页面的逻辑
    @RequestMapping(value = "/web/login"
            , method = RequestMethod.GET)
    public String weblogin_get(@ModelAttribute UserBean user, HttpServletRequest request, ModelMap map) {
        HttpSession session = request.getSession(false);
        ResultBean resultBean = loginInterceptor.checkSession(session);
        if (resultBean.isSuccess()) {
            map.put("user", resultBean.getData());
            return "/user_page";
        } else {
            return "redirect:/hello";
        }
    }

    //表单提交的 路径
    @RequestMapping(value = "/web/login"
            , method = RequestMethod.POST)
    public String weblogin(@ModelAttribute UserBean user, HttpServletRequest request, ModelMap map) {

        System.out.println("/web/login request......");
        String username = user.getName();
        String password = user.getPwd();

        JSONObject object = new JSONObject();
        object.put("name", username);
        object.put("pwd", password);
        ResultBean resultBean = loginControler.login(object, request);
        System.out.println("login --->:" + resultBean);
        if (resultBean.isSuccess()) {
            map.put("user", resultBean.getData());
            return "/user_page";
        } else {
            return "redirect:/hello?result=error";
        }
    }


}

